package com.gxm.调优;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 郭训民
 * @description: TODO
 * @title: STWTest
 * @projectName jsee
 * @date 2022/3/8 16:21
 */
public class STWTest {
    /**
     * 打印线程
     */
    public static class PrintThrad extends Thread {
        private static final long startTime = System.currentTimeMillis();

        @Override
        public void run() {
            while (true) {
                try {
                    long printTime = System.currentTimeMillis() - startTime;
                    //每间100ms打印出这种时间格式，方便和GC日志对比,不过有时余数位为2位要补0，这里不做操作，因为不影响测试结果
                    System.out.println(printTime / 1000 + "." + printTime % 1000);
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 不断新建对象的线程
     */
    public static class AddThread extends Thread {
        HashMap map = new HashMap();

        @Override
        public void run() {
            while (true) {
                try {
                    //map占用内存大于900，则清空，防止内存溢出
                    if (map.size() * 1024 / 1024 / 1024 > 900) {
                        map.clear();
                        System.out.println("map数据被清空");
                    }
                    //不断添加对象到map
                    for (int i = 0; i < 100; i++) {
                        byte[] bytes = new byte[1024];
                        map.put(System.nanoTime(), bytes);
                    }
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new PrintThrad().start();
        new AddThread().start();
        String str = new String("abc");
        Integer i = new Integer(1);
        HashMap map = new HashMap();
    }
}
